package com.adcc.foc.core.api;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by houxy on 2017/1/3.
 */
public class SpringMVCInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String path = request.getServletPath();
        String loginUserId = (String) request.getSession(true).getAttribute("loginUserId");
        String requestType = request.getHeader("X-Requested-With");
        String basePath = request.getContextPath() + "/";
        if ("/".equals(path) || path.indexOf("/checklogin") != -1 || path.indexOf("/randomPic") != -1 || path.indexOf("/genaessecret") != -1 ||path.indexOf("/resetPassword") != -1) {
            return true;
        } else {
            if (loginUserId == null || "".equals(loginUserId)) {
                request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", "org.springframework.security.authentication.BadCredentialsException: ErrorValidateCode");
                if (requestType != null && "XMLHttpRequest".equals(requestType)) {
                    response.setHeader("sessionstatus", "timeout");
                    //向http头添加登录的url
                    response.addHeader("loginPath", basePath);
                    response.setStatus(403);
                } else {
                    response.sendRedirect(basePath);
                }
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
